package geektime.io.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * 通过netty演示服务器
 */
public class NettyEchoServer {
    static final int PORT = Integer.parseInt(System.getProperty("port", "1234"));

    public static void main(String[] args) {
        // Configure the server。EventLoop是netty处理事件的核心机制
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        // 创建EchoServerHandler
        final EchoServerHandler serverHandler = new EchoServerHandler();
        try {
            // ServerBootstrap是服务器端程序的入口，是Netty为简化网络程序配置和关闭等生命周期操作所引入的Bootstrap机制
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {  // 绑定handler用于处理请求
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 它是ChannelHandler链条的容器，每个Channel在创建后，自动被分配一个ChannelPipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(serverHandler);
                    }
                });
            System.out.println("NettyEchoServer waiting...");
            // Start the server synchronized。ChannelFuture是Netty实现异步IO的基础之一，保证了同一个Channel操作的调用顺序
            ChannelFuture channelFuture = sb.bind(PORT).sync();
            // Wait until the server socket is closed
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
